package com.yntx.usercenter.authentication.controller;

import com.yntx.usercenter.authentication.dto.*;
import com.yntx.usercenter.authentication.mapper.UserMapper;
import com.yntx.usercenter.authentication.po.User;
import com.yntx.usercenter.authentication.service.UserService;
import com.yntx.usercenter.authentication.vo.UserVo;
import com.yntx.usercenter.common.config.TenantUserContextHolder;
import com.yntx.usercenter.common.web.ApiResult;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.shardingsphere.infra.hint.HintManager;
import org.springframework.web.bind.annotation.*;

/**
 * 用户控制器
 *
 * @author jielihaofeng
 * @date 2023-04-24 12:15
 */
@RestController
@RequestMapping("/user")
@AllArgsConstructor
public class UserController {

    private UserService userService;
    private UserMapper userMapper;

    /**
     * 注册
     *
     * @param userRegisterDto 用户注册dto
     * @return {@link ApiResult}<{@link UserRegisterResultDto}>
     */
    @PostMapping("/register")
    public ApiResult<Long> register(@RequestBody UserRegisterDto userRegisterDto) {
        return userService.register(userRegisterDto);
    }

    /**
     * 登录
     *
     * @param userLoginDto 用户登录dto
     * @return {@link ApiResult}<{@link UserLoginResultDto}>
     */
    @PostMapping("/login")
    public ApiResult<UserLoginResultDto> login(@RequestBody UserLoginDto userLoginDto) {
        return userService.login(userLoginDto);
    }

    /**
     * 注销
     *
     * @param userLogoutDto 用户注销dto
     * @return {@link ApiResult}<{@link ?}>
     */
    @PostMapping("/logout")
    public ApiResult<?> logout(@RequestBody UserLogoutDto userLogoutDto) {
        return userService.logout(userLogoutDto);
    }

    /**
     * 用户信息
     *
     * @param userInfoDto 用户信息dto
     * @return {@link ApiResult}<{@link UserVo}>
     */
    @PostMapping("/userInfo")
    public ApiResult<UserVo> userInfo(@RequestBody UserInfoDto userInfoDto) {
        return userService.userInfo(userInfoDto);
    }

    @GetMapping("/insert")
    public ApiResult<?> userInfo(String tenantId, Long systemId, Boolean isShareUser) {
        TenantUserContextHolder ctx = TenantUserContextHolder.get();
        ctx.setTenantId(tenantId);
        ctx.setSystemId(String.valueOf(systemId));
        ctx.setIsShareUser(isShareUser);
        TenantUserContextHolder.set(ctx);

        HintManager instance = HintManager.getInstance();
        instance.addDatabaseShardingValue("t_user", tenantId);
        instance.addTableShardingValue("t_user", systemId);
        User user = User.builder()
                .username(tenantId + "-" + RandomStringUtils.randomAlphabetic(8))
                .password("123456")
                .systemId(systemId)
                .systemCode("new")
                .build();
        userMapper.insert(user);
        instance.close();

        TenantUserContextHolder.set(null);

        return ApiResult.ofSuccess();
    }

}
